<template>
  <div class="document-manage-container">
    <el-card class="manage-card">
      <template #header>
        <div class="card-header">
          <h2>文档管理</h2>
          <el-button type="primary" @click="showUploadDialog">上传新文档</el-button>
        </div>
      </template>

      <div class="search-filter-section">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
            <el-input
              v-model="searchQuery"
              placeholder="搜索文档..."
              clearable
              @keyup.enter="searchDocuments"
            >
              <template #append>
                <el-button :icon="Search" @click="searchDocuments"></el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
            <div class="filter-container">
              <el-select v-model="selectedCategory" placeholder="选择分类" clearable @change="filterByCategory" class="filter-item">
                <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
              <el-select v-model="selectedTags" multiple collapse-tags placeholder="选择标签" clearable @change="filterByTags" class="filter-item">
                <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id" />
              </el-select>
            </div>
          </el-col>
        </el-row>
      </div>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
      <div v-else-if="documents.length === 0" class="empty-container">
        <el-empty description="暂无文档" />
      </div>
      <el-table v-else :data="documents" style="width: 100%">
        <el-table-column prop="title" label="标题" min-width="180"></el-table-column>
        <el-table-column prop="category" label="分类" width="120"></el-table-column>
        <el-table-column label="标签" width="180">
          <template #default="scope">
            <el-tag 
              v-for="tag in scope.row.tags" 
              :key="tag" 
              size="small" 
              effect="plain"
              style="margin-right: 5px"
            >
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="version" label="版本" width="80"></el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ new Date(scope.row.createTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="scope">
            {{ new Date(scope.row.updateTime).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="订阅人数" width="100">
          <template #default="scope">
            {{ scope.row.subscriberCount }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220">
          <template #default="scope">
            <el-button size="small" @click="viewDocument(scope.row.id)">查看</el-button>
            <el-button size="small" type="primary" @click="editDocument(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteDocument(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 上传文档对话框 -->
    <el-dialog v-model="uploadDialogVisible" title="上传新文档" width="60%">
      <el-form :model="documentForm" :rules="documentRules" ref="documentFormRef" label-width="100px">
        <el-form-item label="文档标题" prop="title">
          <el-input v-model="documentForm.title" placeholder="请输入文档标题"></el-input>
        </el-form-item>
        <el-form-item label="文档分类" prop="categoryId">
          <el-select v-model="documentForm.categoryId" placeholder="请选择分类">
            <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
          <el-button type="text" @click="showCategoryDialog">管理分类</el-button>
        </el-form-item>
        <el-form-item label="文档标签" prop="tags">
          <el-select
            v-model="documentForm.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或创建标签"
          >
            <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="文档内容" prop="content">
          <el-input
            v-model="documentForm.content"
            type="textarea"
            :rows="10"
            placeholder="请输入文档内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="文件上传">
          <el-upload
            action="#"
            :auto-upload="false"
            :limit="5"
            multiple
            :file-list="fileList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">
                支持各种格式的文件，单个文件不超过20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="uploadDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDocument" :loading="submitting">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分类管理对话框 -->
    <el-dialog v-model="categoryDialogVisible" title="分类管理" width="40%">
      <el-table :data="categories" style="width: 100%">
        <el-table-column prop="name" label="分类名称"></el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button size="small" @click="editCategory(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteCategory(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 20px">
        <el-input v-model="newCategory" placeholder="请输入新分类名称" style="width: 60%"></el-input>
        <el-button type="primary" @click="addCategory" style="margin-left: 10px">添加分类</el-button>
      </div>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog v-model="editCategoryDialogVisible" title="编辑分类" width="30%">
      <el-form :model="categoryForm" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="categoryForm.name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editCategoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateCategory">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索与筛选状态
const searchQuery = ref('')
const selectedCategory = ref('')
const selectedTags = ref([])

// 分页状态
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 数据状态
const loading = ref(true)
const documents = ref([])
const categories = ref([])
const tags = ref([])

// 文档上传表单
const documentFormRef = ref(null)
const uploadDialogVisible = ref(false)
const submitting = ref(false)
const fileList = ref([])

const documentForm = reactive({
  id: null,
  title: '',
  categoryId: null,
  tags: [],
  content: '',
  files: []
})

const documentRules = {
  title: [{ required: true, message: '请输入文档标题', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择文档分类', trigger: 'change' }],
  content: [{ required: true, message: '请输入文档内容', trigger: 'blur' }]
}

// 分类管理
const categoryDialogVisible = ref(false)
const editCategoryDialogVisible = ref(false)
const newCategory = ref('')
const categoryForm = reactive({
  id: null,
  name: ''
})

// 初始化数据
onMounted(async () => {
  try {
    await Promise.all([
      fetchDocuments(),
      fetchCategories(),
      fetchTags()
    ])
  } catch (error) {
    console.error('Failed to load initial data:', error)
    ElMessage.error('加载数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
})

// 获取文档列表
async function fetchDocuments() {
  loading.value = true
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/documents/manage', {
    //   params: {
    //     page: currentPage.value,
    //     size: pageSize.value,
    //     query: searchQuery.value,
    //     categoryId: selectedCategory.value,
    //     tags: selectedTags.value.join(',')
    //   }
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟分页数据
    documents.value = Array.from({ length: 10 }, (_, i) => ({
      id: i + 1,
      title: `管理文档 ${i + 1}`,
      category: '技术文档',
      tags: ['Vue', 'JavaScript', '前端'],
      version: '1.0',
      createTime: new Date().getTime() - Math.floor(Math.random() * 10000000),
      updateTime: new Date().getTime() - Math.floor(Math.random() * 5000000),
      subscriberCount: Math.floor(Math.random() * 100)
    }))
    
    total.value = 100 // 模拟总数
  } catch (error) {
    console.error('Failed to fetch documents:', error)
    ElMessage.error('获取文档列表失败')
  } finally {
    loading.value = false
  }
}

// 获取分类列表
async function fetchCategories() {
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/categories')
    
    // 模拟数据
    categories.value = [
      { id: 1, name: '技术文档' },
      { id: 2, name: '用户手册' },
      { id: 3, name: '产品说明' },
      { id: 4, name: '内部流程' },
      { id: 5, name: '培训资料' }
    ]
  } catch (error) {
    console.error('Failed to fetch categories:', error)
  }
}

// 获取标签列表
async function fetchTags() {
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/tags')
    
    // 模拟数据
    tags.value = [
      { id: 1, name: 'Vue' },
      { id: 2, name: 'JavaScript' },
      { id: 3, name: '前端' },
      { id: 4, name: 'Java' },
      { id: 5, name: '后端' },
      { id: 6, name: '数据库' }
    ]
  } catch (error) {
    console.error('Failed to fetch tags:', error)
  }
}

// 搜索文档
function searchDocuments() {
  currentPage.value = 1
  fetchDocuments()
}

// 筛选
function filterByCategory() {
  currentPage.value = 1
  fetchDocuments()
}

function filterByTags() {
  currentPage.value = 1
  fetchDocuments()
}

// 分页处理
function handleSizeChange(size) {
  pageSize.value = size
  fetchDocuments()
}

function handleCurrentChange(page) {
  currentPage.value = page
  fetchDocuments()
}

// 上传文档相关
function showUploadDialog() {
  // 重置表单
  documentForm.id = null
  documentForm.title = ''
  documentForm.categoryId = null
  documentForm.tags = []
  documentForm.content = ''
  documentForm.files = []
  fileList.value = []
  
  uploadDialogVisible.value = true
}

function handleFileChange(file, fileList) {
  documentForm.files = fileList.map(f => f.raw)
}

function handleFileRemove(file, fileList) {
  documentForm.files = fileList.map(f => f.raw)
}

// 提交文档
async function submitDocument() {
  if (!documentFormRef.value) return
  
  await documentFormRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        // 这里替换为实际的API调用
        // 如果是新增文档
        // const formData = new FormData()
        // formData.append('title', documentForm.title)
        // formData.append('categoryId', documentForm.categoryId)
        // formData.append('content', documentForm.content)
        // documentForm.tags.forEach(tag => formData.append('tags', tag))
        // documentForm.files.forEach(file => formData.append('files', file))
        
        // if (documentForm.id) {
        //   // 编辑已有文档
        //   formData.append('id', documentForm.id)
        //   await axios.put('/api/documents', formData)
        // } else {
        //   // 新增文档
        //   await axios.post('/api/documents', formData)
        // }
        
        // 模拟成功
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        ElMessage.success(documentForm.id ? '文档更新成功' : '文档上传成功')
        uploadDialogVisible.value = false
        fetchDocuments() // 刷新列表
      } catch (error) {
        console.error('Failed to submit document:', error)
        ElMessage.error(documentForm.id ? '文档更新失败' : '文档上传失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 查看、编辑、删除文档
function viewDocument(id) {
  ElMessage.info(`查看文档 ID: ${id}`)
}

function editDocument(doc) {
  // 填充表单
  documentForm.id = doc.id
  documentForm.title = doc.title
  documentForm.categoryId = categories.value.find(c => c.name === doc.category)?.id
  documentForm.tags = doc.tags.map(tagName => {
    const tag = tags.value.find(t => t.name === tagName)
    return tag ? tag.id : tagName
  })
  documentForm.content = '这里是文档内容示例，实际中应该从API获取完整内容。'
  fileList.value = [] // 实际中应该显示已有附件
  
  uploadDialogVisible.value = true
}

async function deleteDocument(id) {
  try {
    await ElMessageBox.confirm('确定要删除此文档吗？该操作不可逆。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete(`/api/documents/${id}`)
    
    // 模拟删除成功
    documents.value = documents.value.filter(doc => doc.id !== id)
    total.value--
    
    ElMessage.success('文档删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete document:', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }
}

// 分类管理相关
function showCategoryDialog() {
  categoryDialogVisible.value = true
}

async function addCategory() {
  if (!newCategory.value.trim()) {
    ElMessage.warning('分类名称不能为空')
    return
  }
  
  try {
    // 这里替换为实际的API调用
    // const response = await axios.post('/api/categories', { name: newCategory.value })
    
    // 模拟添加成功
    const newId = categories.value.length + 1
    categories.value.push({ id: newId, name: newCategory.value })
    
    newCategory.value = ''
    ElMessage.success('分类添加成功')
  } catch (error) {
    console.error('Failed to add category:', error)
    ElMessage.error('添加分类失败')
  }
}

function editCategory(category) {
  categoryForm.id = category.id
  categoryForm.name = category.name
  editCategoryDialogVisible.value = true
}

async function updateCategory() {
  if (!categoryForm.name.trim()) {
    ElMessage.warning('分类名称不能为空')
    return
  }
  
  try {
    // 这里替换为实际的API调用
    // await axios.put(`/api/categories/${categoryForm.id}`, { name: categoryForm.name })
    
    // 模拟更新成功
    const index = categories.value.findIndex(c => c.id === categoryForm.id)
    if (index !== -1) {
      categories.value[index].name = categoryForm.name
    }
    
    editCategoryDialogVisible.value = false
    ElMessage.success('分类更新成功')
  } catch (error) {
    console.error('Failed to update category:', error)
    ElMessage.error('更新分类失败')
  }
}

async function deleteCategory(id) {
  try {
    await ElMessageBox.confirm('确定要删除此分类吗？相关文档的分类将变为未分类。', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete(`/api/categories/${id}`)
    
    // 模拟删除成功
    categories.value = categories.value.filter(c => c.id !== id)
    
    ElMessage.success('分类删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete category:', error)
      ElMessage.error('删除分类失败')
    }
  }
}
</script>

<style scoped>
.document-manage-container {
  padding: 20px;
  height: 100%;
}

.manage-card {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.card-header h2 {
  margin: 0;
}

.search-filter-section {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-item {
  flex: 1;
  min-width: 180px;
}

.loading-container, 
.empty-container {
  padding: 40px 0;
  text-align: center;
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-container {
    flex-direction: column;
    width: 100%;
  }
  
  .filter-item {
    width: 100%;
  }
}
</style> 